import React, { useState, useEffect, useRef } from 'react';
import {
  Button,
  Checkbox,
  Form,
  Input,
  InputNumber,
  message,
  Select,
  Space,
  Tabs,
  Modal,
  Radio,
  Popconfirm,
} from 'antd';
import { FormattedMessage, useIntl } from 'umi';
import { EditableProTable } from '@ant-design/pro-table';
import type { ProColumns } from '@ant-design/pro-table';
import request from '@/utils/request';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { OpMasterSelect, ResourceGrpSelect, ResourceSelect } from '@/components/FormItemSelect';

const { TabPane } = Tabs;
const { confirm } = Modal;
const apiURL = '/api/services/app/JobOper/';

const JobOprEdit = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [defTab, setDefTab] = useState('MTL1');
  const [datas, setDatas] = useState<any>(null);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [asmList, setAsmList] = useState<any[]>([]);
  const [record, setRecord] = useState<any>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [editableKeys, setEditableKeys] = useState<any[]>([]);
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    console.log(props.datas);
    initData();
  }, [props.datas]);

  useEffect(() => {
    setDatas(props.datas);
    setDataSource(props.datas?.boos);
    setAsmList(props.datas?.boms);
    setRecord(props.record);
    formRef.current.setFieldsValue({ JobOper: props.record });
  }, [props.record, props.datas]);

  const initData = () => {
    setDatas(props.datas);
    setDataSource(props.datas?.boos);
    setAsmList(props.datas?.boms);
    setRecord(props.record);
    formRef.current.setFieldsValue({ JobOper: props.record });
  };

  const onChange = (values: any[]) => {
    setDataSource(values);
  };

  const setSelRows = (keys: any, rows: any) => {
    setRecord(rows);
    setSelectedRowKeys(keys);
  };

  const doDel = () => {
    confirm({
      title: intl.formatMessage({id:'pages.warning'}),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({id:'pages.deleteConfirm'}),
      onOk() {
        setLoading(true);
        request(apiURL + 'DelBatch', {
          method: 'POST',
          data: selectedRowKeys,
        }).then((response) => {
          if (response.success) {
            const newDataSource = datas.boos.filter((o: any) => selectedRowKeys.indexOf(o.id) < 0);
            setDataSource(newDataSource);
            resetForm();
            if (props.reloadData) {
              props.reloadData('Del', 'JobOper', newDataSource);
            }
          }
        });
        setLoading(false);
      },
    });
  };

  const onFinish = (values: any) => {
    saveJobData(values.JobOper, apiURL);
  };

  const saveJobData = (data: any, api: string) => {
    let act = 'New';
    let method = 'POST';
    if (data.id) {
      act = 'Update';
      method = 'PUT';
    }
    try {
      const asmb = asmList.filter((o: any) => o.assemblySeq == data.assemblySeq)[0];
      data.partNum = asmb.partNum;
      data.revisionNum = asmb.revisionNum;
      data.partDescription = asmb.partDescription;
    } catch {
      message.error('请选择半成品');
      return;
    }
    data.opDesc = data.opCode;
    request(api + act, {
      method: method,
      data: data,
    }).then((response) => {
      if (response && response.success) {
        message.success('保存成功！');
        if (props.reloadData) {
          props.reloadData(act, 'JobOper', response.result);
        }
      }
      setLoading(false);
    });
  };

  const resetForm = () => {
    formRef.current.resetFields();
    const JobOper: any = { jobNum: datas?.jobHead.jobNum };
    formRef.current.setFieldsValue({ JobOper });
    setRecord(JobOper);
  };

  const delObj = (id: any) => {
    setSelectedRowKeys([id]);
    doDel();
  };

  const tabSwitch = (key: any) => {
    setDefTab(key);
  };

  const switchEdit = (key: string, record: any) => {
    setDefTab(key);
    setRecord(record);
    formRef.current.setFieldsValue({ JobOper: record });
  };

  const setDataSourceFunc = (params?: any, data?: any) => {
    if (params?.opCode) data = data.filter((o: any) => o.opCode == params.opCode);
    if (params?.partNum) data = data.filter((o: any) => o.partNum == params.partNum);
    if (params?.partDescription)
      data = data.filter((o: any) => o.partDescription.indexOf(params.partDescription) >= 0);
    if (params?.opDesc) data = data.filter((o: any) => o.opDesc.indexOf(params.opDesc) >= 0);
    return {
      data,
      total: data.length,
      success: true,
    };
  };

  const columns: ProColumns[] = [
    {
      title: <FormattedMessage id="pages.jobNum" />,
      dataIndex: 'jobNum',
      width: 100,
      hideInSearch: true,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      width: 120,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      ellipsis: true,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.oprSeq" />,
      dataIndex: 'oprSeq',
      width: 65,
      hideInSearch: true,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.opCode" />,
      dataIndex: 'opCode',
      width: 120,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.opDesc" />,
      dataIndex: 'opDesc',
      ellipsis: true,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.completeQty" />,
      dataIndex: 'completeQty',
      editable: false,
      hideInSearch: true,
      width: 80,
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      width: 80,
      editable: false,
      dataIndex: 'stdFormat',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.operation" />,
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (text, record, _, action) => [
        <Popconfirm
          title={<FormattedMessage id="pages.confirmDelete" />}
          onConfirm={() => delObj(record.id)}
        >
          <a>
            <FormattedMessage id="pages.delete" />
          </a>
        </Popconfirm>,
      ],
    },
  ];

  const layout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 15 },
  };

  return (
    <>
      <Tabs defaultActiveKey={defTab} activeKey={defTab} onChange={tabSwitch}>
        <TabPane tab={<FormattedMessage id="pages.attribute" />} key="MTL1">
          <Form {...layout} ref={formRef} onFinish={onFinish}>
            <Form.Item name={['JobOper', 'id']} hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item
              name={['JobOper', 'jobNum']}
              label={<FormattedMessage id="pages.jobNum" />}
              rules={[{ required: true, message: <FormattedMessage id="pages.jobNum.required" /> }]}
            >
              <Input disabled style={{ width: 200 }} />
            </Form.Item>
            <Form.Item name={['JobOper', 'partDescription']} hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item name={['JobOper', 'partNum']} hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item name={['JobOper', 'revisionNum']} hidden={true}>
              <Input />
            </Form.Item>
            <Form.Item
              name={['JobOper', 'assemblySeq']}
              required
              label={<FormattedMessage id="pages.assemblySeq" />}
            >
              <Select style={{ width: 400 }}>
                {asmList?.map((item: any) => {
                  return (
                    <Select.Option value={item.assemblySeq} key={item.id}>
                      {item.assemblySeq} - {item.partNum} - {item.partDescription}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item
              name={['JobOper', 'oprSeq']}
              label={<FormattedMessage id="pages.oprSeq" />}
              rules={[{ required: false, message: <FormattedMessage id="pages.oprSeq.required" /> }]}
            >
              <InputNumber min={0} step={10} disabled />
            </Form.Item>
            <Form.Item label={<FormattedMessage id="pages.prodStandard" />} required>
              <Input.Group compact>
                <Form.Item
                  noStyle
                  name={['JobOper', 'prodStandard']}
                  rules={[
                    { required: true, message: <FormattedMessage id="pages.prodStandard.required" /> },
                  ]}
                >
                  <InputNumber min={0} />
                </Form.Item>
                <Form.Item
                  noStyle
                  name={['JobOper', 'stdFormat']}
                  rules={[
                    { required: true, message: <FormattedMessage id="pages.stdFormat.required" /> },
                  ]}
                >
                  <Select
                    placeholder={<FormattedMessage id="pages.hourPerPiece" />}
                    style={{ width: 90 }}
                  >
                    <Select.Option value="HP">
                      <FormattedMessage id="pages.hourPerPiece" />
                    </Select.Option>
                    <Select.Option value="MP">
                      <FormattedMessage id="pages.minutePerPiece" />
                    </Select.Option>
                    <Select.Option value="PM">
                      <FormattedMessage id="pages.piecePerMinute" />
                    </Select.Option>
                    <Select.Option value="OH">
                      <FormattedMessage id="pages.piecePerHour" />
                    </Select.Option>
                  </Select>
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <OpMasterSelect
              width={200}
              labelInValue={false}
              rules={[{ required: true, message: <FormattedMessage id="pages.opCode.required" /> }]}
              showSearch={false}
              name={['JobOper', 'opCode']}
              label={<FormattedMessage id="pages.opCode" />}
            />
            <Form.Item style={{ marginBottom: 0 }} wrapperCol={{ offset: 3 }}>
              <Input.Group compact>
                <Form.Item name={['JobOper', 'subContract']} valuePropName="checked">
                  <Checkbox>
                    <FormattedMessage id="pages.subContract" />
                  </Checkbox>
                </Form.Item>
                <Form.Item name={['JobOper', 'finalOpr']} valuePropName="checked">
                  <Checkbox>
                    <FormattedMessage id="pages.finalOpr" />
                  </Checkbox>
                </Form.Item>
                <Form.Item name={['JobOper', 'autoReceive']} valuePropName="checked">
                  <Checkbox>
                    <FormattedMessage id="pages.autoReceive" />
                  </Checkbox>
                </Form.Item>
                <Form.Item name={['JobOper', 'opComplete']} valuePropName="checked">
                  <Checkbox disabled>
                    <FormattedMessage id="pages.complete" />
                  </Checkbox>
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item
              name={['JobOper', 'schedRelation']}
              label={<FormattedMessage id="pages.schedRelation" />}
              rules={[
                { required: true, message: <FormattedMessage id="pages.schedRelation.required" /> },
              ]}
            >
              <Radio.Group>
                <Radio value="SS">
                  <FormattedMessage id="pages.sched-SS" />
                </Radio>
                <Radio value="FS">
                  <FormattedMessage id="pages.sched-FS" />
                </Radio>
                <Radio value="FF">
                  <FormattedMessage id="pages.sched-FF" />
                </Radio>
              </Radio.Group>
            </Form.Item>
            <ResourceGrpSelect
              width={200}
              rules={[
                { required: true, message: <FormattedMessage id="pages.resourceGrpID.required" /> },
              ]}
              showSearch={false}
              name={['JobOper', 'resourceGrpID']}
              label={<FormattedMessage id="pages.resourceGrpID" />}
            />
            <ResourceSelect
              width={200}
              rules={[{ required: true, message: <FormattedMessage id="pages.resourceID.required" /> }]}
              showSearch={false}
              name={['JobOper', 'resourceID']}
              label={<FormattedMessage id="pages.resourceID" />}
            />
            <Form.Item
              label={<FormattedMessage id="pages.commentText" />}
              name={['JobOper', 'commentText']}
            >
              <Input.TextArea />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: layout.labelCol.span }}>
              <Space>
                <Button type="primary" htmlType="submit" loading={loading}>
                  <FormattedMessage id="pages.save" />
                </Button>
                <Button onClick={resetForm}>
                  <FormattedMessage id="pages.new" />
                </Button>
                <Button danger disabled={!record?.id} onClick={() => delObj(record.id)}>
                  <FormattedMessage id="pages.delete" />
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </TabPane>
        <TabPane tab={<FormattedMessage id="pages.list" />} key="MTL2" forceRender>
          <EditableProTable
            rowKey="id"
            scroll={{
              x: 960,
            }}
            loading={loading}
            columns={columns}
            recordCreatorProps={false}
            value={dataSource}
            onChange={onChange}
            request={async (params = {}, sort, filter) => {
              return setDataSourceFunc(params, datas?.boos);
            }}
            rowSelection={{
              selectedRowKeys,
              onChange: setSelRows,
            }}
            cardBordered
            search={{
              filterType: 'light',
            }}
            onRow={(record) => {
              return {
                onDoubleClick: (event) => {
                  switchEdit('MTL1', record);
                },
              };
            }}
            tableAlertRender={false}
            tableAlertOptionRender={false}
            editable={{
              type: 'multiple',
              actionRender: (row, config, dom) => [dom.save, dom.cancel],
              onSave: async (rowKey, data, row) => {
                setSelectedRowKeys([]);
              },
              editableKeys,
              onChange: (keys: any) => {
                console.log(keys);
              },
            }}
            pagination={{
              pageSize: 10,
            }}
            toolBarRender={() => [
              <Button key="button" type="primary" danger onClick={doDel}>
                <FormattedMessage id="pages.delete.batch" />
              </Button>,
            ]}
          />
        </TabPane>
      </Tabs>
    </>
  );
};

export default JobOprEdit;
